﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Generic.Helper.Configure
{
    public static class ConfigureServicesExtensions
    {
        public static void JwtConfigure(this IServiceCollection services, IConfiguration configuration)
        {
            var jwtOptions = configuration.GetSection(JwtOptions.Position).Get<JwtOptions>();
            if (jwtOptions.Isenabled)
            {
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.Audience = jwtOptions.Audience;

                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            // The signing key must match!
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.Securitykey)),

                            // Validate the JWT Issuer (iss) claim
                            ValidateIssuer = true,
                            ValidIssuer = jwtOptions.Issuer,

                            // Validate the JWT Audience (aud) claim
                            ValidateAudience = true,
                            ValidAudience = jwtOptions.Audience,

                            // Validate the token expiry
                            ValidateLifetime = true,

                            // If you want to allow a certain amount of clock drift, set that here
                            ClockSkew = TimeSpan.FromSeconds(jwtOptions.ClockSkewSecond)
                        };
                    });

            }
        }
    }
}

